import * as echarts from 'echarts';
import {getPostAnalysis, listByPost, listUser} from "@/api/system/user";
import mixins from "@/views/train/mixins";
import {
  commonTemplates,
  examRanking,
  getAnalysisData,
  getTrainLineChart,
  historyExamFirst,
  paperErrorProportion,
  passingRate,
  trainErrorProportion,
  trainPaperList,
  userRanking
} from "@/api/train/Analysis";
import {listExamTestPaperModule} from "@/api/train/base/ExamTestPaperModule";
import {USER_TYPE} from "@/views/train/Enums";
import {listPost} from "@/api/system/post";

export default {
  name: "StatisticalAnalysis",
  mixins: [mixins],
  components: {},
  data() {
    return {
      trainQueryParams: {
        userId: '',
        dateRange: [],
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      width: "100%",
      height: "320px",
      chart: null,
      options: {
        userList: [],
        userMap: {},
        USER_TYPE: USER_TYPE,
        testPaperModuleList: [],
      },
      // 岗位能力
      postAbilities: [],
      // 岗位等级
      postLevels: [],
      // 岗位统计
      posts: [],
      // 科目,知识点训练量占比
      trainAll: [],
      // 科目,知识点训练量错误占比
      trainError: [],
      // 一段时间训练题目数量及错题数量
      trainLineChart: {
        date: [],
        all: [],
        error: [],
      },
      // 无线滚动
      userRanking: {
        data: [],
        pagination: {
          pageNum: 1,
          pageSize: 10,
        },
        noMore: false,
        loading: false,
      },
      commonTemplates: {
        data: [],
      },
      trainErrorProportion: {
        data: {}
      },
      trainPaper: {
        data: [],
        params: {
          name: '',
          testPaperModuleId: '',
          userId: '',
        },
        loading: false,
        noMore: false,
        pagination: {
          pageNum: 1,
          pageSize: 10,
          total: 100,
        },
      },
      examRanking: {
        data: []
      },
      passingRate: {
        yAxis: [],
        xAxis: []
      },
      paperErrorProportion: {
        data: []
      },
      historyExamFirst: {
        data: [],
      },
      // 岗位总览相关
      // 岗位列表
      postList: [],
      // 岗位下的人员信息
      postUserMap: {},
      // 当前的岗位
      activePost: '0',
    }
  },
  watch: {
    trainQueryParams: {
      handler() {
        this.handleQueryTrain()
        this.handleTrainLineChart()
      },
      immediate: true,
      deep: true
    },
    activePost(postId) {
      if (!this.postUserMap[postId]) {
        listByPost({postId}).then(res => {
          this.$set(this.postUserMap, postId, res.data)
        })
      }
    }
  },
  methods: {
    initOptions() {
      // 人员列表
      listUser().then(res => {
        this.options.userList = res.rows
        res.rows.forEach(row => {
          this.options.userMap[row.userId] = row.nickName
        })
      })
      // 模拟试卷模板列表
      listExamTestPaperModule({userType: this.options.USER_TYPE.enums.TRAIN.value}).then(res => {
        this.options.testPaperModuleList = res.rows
      })
    },
    // 岗位分析
    handleGetPostAnalysis() {
      getPostAnalysis().then(res => {
        // 岗位能力
        this.postAbilities = res.data.postAbilities
        // 岗位等级
        this.postLevels = res.data.postLevels
        // 岗位统计
        this.posts = res.data.posts
        this.initChart1()
      });
    },
    initTrainLineChart() {
      var chart = echarts.init(this.$refs.trainLineChart);
      var option = {
        title: {
          text: '🕢️一段时间训练题目数量及错题数量'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['错题', '全部']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.trainLineChart.date
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '错题',
            type: 'line',
            stack: 'Total',
            data: this.trainLineChart.error,
          },
          {
            name: '全部',
            type: 'line',
            stack: 'Total',
            data: this.trainLineChart.all,
          },
        ]
      };
      chart.setOption(option);
    },
    initzxzb1() {
      var chart = echarts.init(this.$refs.zxzb1);
      var option = {
        // silent: true,
        title: {
          text: '🌈科目-知识点',
          subtext: '训练数量占比',
          // top: 'bottom',
          left: 'left'
        },
        tooltip: {
          show: true
        },
        series: [
          {
            radius: ['15%', '80%'],
            type: 'sunburst',
            sort: undefined,
            emphasis: {
              focus: 'ancestor'
            },
            data: this.trainAll,
            label: {
              color: '#000',
              textBorderColor: '#fff',
              textBorderWidth: 2,
            },
            levels: [
              {},
              {
                itemStyle: {
                  color: '#5470C6'
                },
                label: {
                  rotate: 'radial'
                }
              },
              {
                itemStyle: {
                  color: '#73C0DE'
                },
                label: {
                  rotate: 'tangential'
                }
              },
              {
                itemStyle: {
                  color: '#91CC75'
                },
                label: {
                  rotate: 0
                }
              }
            ]
          }
        ]
      };
      chart.setOption(option);
    },
    initzxzb2() {
      var chart = echarts.init(this.$refs.zxzb2);
      var option = {
        // silent: true,
        tooltip: {
          show: true
        },
        title: {
          text: '🌈各科目-知识点',
          subtext: '错误数量占比',
          // top: 'bottom',
          left: 'left'
        },
        series: [
          {
            radius: ['15%', '80%'],
            type: 'sunburst',
            sort: undefined,
            emphasis: {
              focus: 'ancestor'
            },
            data: this.trainError,
            label: {
              color: '#000',
              textBorderColor: '#fff',
              textBorderWidth: 2,
            },
            levels: [
              {},
              {
                itemStyle: {
                  color: '#5470C6'
                },
                label: {
                  rotate: 'radial'
                }
              },
              {
                itemStyle: {
                  color: '#73C0DE'
                },
                label: {
                  rotate: 'tangential'
                }
              },
              {
                itemStyle: {
                  color: '#EE6666'
                },
                label: {
                  rotate: 0
                }
              }
            ]
          }
        ]
      };
      chart.setOption(option);
    },
    // 人员统计
    initChart1() {
      this.chart = echarts.init(this.$refs.gangwei);
      var option = {
        title: [
          {
            text: '人员统计',
            left: 'center'
          },
          {
            subtext: '岗位统计',
            left: '16.67%',
            top: '55%',
            textAlign: 'center'
          },
          {
            subtext: '岗位能力',
            left: '50%',
            top: '55%',
            textAlign: 'center'
          },
          {
            subtext: '岗位等级',
            left: '83.33%',
            top: '55%',
            textAlign: 'center'
          }
        ],
        tooltip: {
          show: true
        },
        series: [
          {
            type: 'pie',
            radius: '25%',
            center: ['50%', '50%'],
            data: this.posts,
            label: {
              position: 'outer',
              alignTo: 'none',
              bleedMargin: 5
            },
            left: 0,
            right: '66.6667%',
            top: -250,
            bottom: 0
          },
          {
            type: 'pie',
            radius: '25%',
            center: ['50%', '50%'],
            data: this.postAbilities,
            label: {
              position: 'outer',
              alignTo: 'none',
              bleedMargin: 5
            },
            left: '33.3333%',
            right: '33.3333%',
            top: -250,
            bottom: 0
          },
          {
            type: 'pie',
            radius: '25%',
            center: ['50%', '50%'],
            data: this.postLevels,
            label: {
              position: 'outer',
              alignTo: 'none',
              margin: 20
            },
            left: '66.6667%',
            right: 0,
            top: -250,
            bottom: 0
          }
        ]
      };
      this.chart.setOption(option);
    },
    // 旭日图
    handleQueryTrain() {
      let trainQueryParams = {
        userId: this.trainQueryParams.userId,
        startDate: this.trainQueryParams.dateRange[0],
        endDate: this.trainQueryParams.dateRange[1]
      }
      getAnalysisData(trainQueryParams).then(res => {
        this.trainAll = res.data.all
        this.trainError = res.data.error
        this.initzxzb1()
        this.initzxzb2()
      })
    },

    // ------------------------------------------------------------训练,模拟相关
    // 一段时间训练题目数量及错题数量
    handleTrainLineChart() {
      let trainQueryParams = {
        userId: this.trainQueryParams.userId,
        startDate: this.trainQueryParams.dateRange[0],
        endDate: this.trainQueryParams.dateRange[1]
      }
      getTrainLineChart(trainQueryParams).then(res => {
        this.trainLineChart.date = res.data.xdatas
        this.trainLineChart.error = res.data.ydatas1
        this.trainLineChart.all = res.data.ydatas
        this.initTrainLineChart()
      })
    },
    handleUserRanking() {
      if (this.userRanking.pagination.pageSize * this.userRanking.pagination.pageNum >= this.userRanking.pagination.total) {
        this.userRanking.noMore = true
        return
      }
      this.userRanking.loading = true
      userRanking({
        pageSize: this.userRanking.pagination.pageSize,
        pageNum: this.userRanking.pagination.pageNum
      }).then(res => {
        this.userRanking.data.push(...res.rows)
        this.userRanking.pagination.total = res.total
        this.userRanking.loading = false
      }).finally(() => {
      })
      this.userRanking.pagination.pageNum++
    },
    //训练错误数量占比饼状图
    handleTrainErrorProportion() {
      trainErrorProportion().then(res => {
        this.trainErrorProportion.data = [
          {name: '正确', value: res.data.all - res.data.error},
          {name: '错误', value: res.data.error},
        ]
        this.initTrainErrorProportion()
      })
    },
    initTrainErrorProportion() {
      let chart = echarts.init(this.$refs.trainErrorProportion);
      let option = {
        title: {
          // text: '错误数量占比',
          text: '模拟训练',
          left: 'left',
          // top: 'bottom',
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'center'
        },
        series: [
          {
            // name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: this.trainErrorProportion.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      chart.setOption(option)
    },


    // 模拟训练-常用模板
    handleCommonTemplates() {
      commonTemplates().then(res => {
        this.commonTemplates.data = res.data
      })
    },
    //   模拟训练-试卷列表
    handleTrainPaperList(reload = false) {
      if (reload) {
        this.trainPaper.loading = true
        this.trainPaper.noMore = false
        this.trainPaper.pagination.pageNum = 1
        trainPaperList({
          ...this.trainPaper.params,
          pageSize: this.trainPaper.pagination.pageSize,
          pageNum: this.trainPaper.pagination.pageNum
        }).then(res => {
          this.trainPaper.data = res.rows
          this.trainPaper.pagination.total = res.total
          this.trainPaper.loading = false
        }).finally(() => {
        })
      } else {
        if (this.trainPaper.pagination.pageSize * this.trainPaper.pagination.pageNum >= this.trainPaper.pagination.total) {
          this.trainPaper.noMore = true
          return
        }
        this.trainPaper.loading = true
        trainPaperList({
          ...this.trainPaper.params,
          pageSize: this.trainPaper.pagination.pageSize,
          pageNum: this.trainPaper.pagination.pageNum
        }).then(res => {
          this.trainPaper.data.push(...res.rows)
          this.trainPaper.pagination.total = res.total
          this.trainPaper.loading = false
        }).finally(() => {
        })
        this.trainPaper.pagination.pageNum++
      }
    },
    loadTrainPaperList() {
      this.handleTrainPaperList(false)
    },
    // -----------------------------------------------------------考试相关
    //   近三次考试排名
    handleExamRanking() {
      examRanking().then(res => {
        let data = {}
        Object.keys(res.data).forEach(exam => {
          let examName = res.data[exam][0].name
          data[exam] = {
            papers: res.data[exam],
            name: examName
          }
        })
        this.examRanking.data = data
      })
    },
    // 近十次考试通过率
    handlePassingRate() {
      passingRate().then(res => {
        let xAxis = [], yAxis = []
        res.data.forEach(e => {
          xAxis.push(e.paperName)
          yAxis.push(e.passRate)
        })
        this.passingRate.xAxis = xAxis
        this.passingRate.yAxis = yAxis
        this.initPassingRate()
      })
    },
    // 近十次考试通过率
    initPassingRate() {
      let chart = echarts.init(this.$refs.passingRate)
      let option = {
        title: {
          text: '📢近十次考试通过率',
          // top: 'center',
          left: 'left',
        },
        xAxis: {
          type: 'category',
          data: this.passingRate.xAxis
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.passingRate.yAxis,
            type: 'line'
          }
        ],
        tooltip: {
          trigger: 'axis'
        },
      };
      chart.setOption(option)
    },
    handlePaperErrorProportion() {
      paperErrorProportion().then(res => {
        this.paperErrorProportion.data = [
          {name: '正确', value: res.data.all - res.data.error},
          {name: '错误', value: res.data.error}]
        this.initPaperErrorProportion()
      })
    },
    initPaperErrorProportion() {
      let chart = echarts.init(this.$refs.paperErrorProportion);
      let option = {
        title: {
          text: '⭕️错误数量占比',
          subtext: '知识点-科目',
          left: 'left',
          // top: 'bottom',
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'center'
        },
        series: [
          {
            // name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: this.paperErrorProportion.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      chart.setOption(option)
    },


    handleHistoryExamFirst() {
      historyExamFirst().then(res => {
        // 每五组作为一次
        let data = []
        let index = 0
        let length = 5
        while (index < res.data.length) {
          data.push(res.data.slice(index, index + length))
          index += length
        }
        this.historyExamFirst.data = data
        console.log(this.historyExamFirst.data)
      })
    },
    // 岗位总览
    handlePostAnalysis() {
      // 获取岗位列表
      listPost().then(res => {
        this.postList = res.rows || []
        if (Array.isArray(this.postList) && this.postList.length) {
          this.activePost = this.postList[0].postId
        }
      })
    },

  },
  mounted() {
    this.initOptions()
    this.$nextTick(() => {
      this.handleCommonTemplates()
      this.handleTrainErrorProportion()
      this.handleTrainPaperList()
      this.handleUserRanking()
      this.handleGetPostAnalysis()
      this.handleExamRanking()
      this.handlePassingRate()
      this.handlePaperErrorProportion()
      this.handleHistoryExamFirst()
      this.handlePostAnalysis()
    })
  },
  created() {
  }
}
